<?php

namespace app\merchants\controller;

use app\common\libs\Excel;
use app\common\validate\virtual\VirtualUsedLogValid;
use app\merchants\loader\Services;
use think\Exception;

/**
 * 虚码审核管理（日志）
 */
class VirtualUsedLog extends ApiBase
{


    /**
     * 虚码使用记录
     * @param $getData
     * @return array[]
     */
    private function formatWhereUsedLog($getData, &$option)
    {

        $merId = $this->adminUser['mer_id'];

        $where[] = ['mer_id', '=', $merId];

        if (!empty($getData['shop_id'])) {
            $where[] = ['shop_id', '=', $getData['shop_id']];
        }

        if (!empty($getData['vp_id'])) {
            $where[] = ['vp_id', '=', $getData['vp_id']];
        }
        if (!empty($this->adminUser['sub_admin_ids'])) {
            $where[] = ['admin_id', 'in', $this->adminUser['sub_admin_ids']];
        }
        if (!empty($getData['admin_id'])) {
            $where[] = ['admin_id', '=', $getData['admin_id']];
        }
        if (!empty($getData['salesman_id'])) {
            $where[] = ['salesman_id', '=', $getData['salesman_id']];
        }
        $stime = trim($getData['start_time'] ?? '');
        $etime = trim($getData['end_time'] ?? '');
        if (!empty($stime) && !empty($etime)) {
            $where[] = ['create_at', 'between', [$stime . ' 00:00:00', $etime . ' 23:59:59']];
        } else {
            if (!empty($stime)) {
                $where[] = ['create_at', '>=', $stime];
            }
            if (!empty($etime)) {
                $where[] = ['create_at', '<=', $etime];
            }
        }
        // 状态
        if (isset($getData['status']) && ($status = trim($getData['status'])) !== '' && $status !== 'all') {
            $where[] = ['a.status', '=', $status];
        }
        if (!empty($getData['product']) && is_numeric($getData['product'])) {
            $option['where_raw'] = "product::jsonb @> '[{\"code\":" . "\"" . $getData['product'] . "\"" . "}]'";
        }
        $option['where'] = $where;
    }

    /**
     * 条件组合
     */
    private function getWhere($data): array
    {
        //商户
        $where[] = ['mer_id', '=', $this->adminUser['mer_id']];


        //状态
        if (isset($getData['status']) && ($status = trim($getData['status'])) !== '' && $status !== 'all') {
            $where[] = ['status', '=', $status];
        }
        //门店
        if (!empty($data['shop_id'])) {
            $where[] = ['shop_id', '=', $data['shop_id']];
        }
        //活动
        if (!empty($data['vp_id'])) {
            $where[] = ['vp_id', '=', $data['vp_id']];
        }

        //导购
        if (!empty($data['salesman_id'])) {
            $where[] = ['salesman_id', '=', $data['salesman_id']];
        }

        //审核人或门店名称
        if (!empty($data['keyword'])) {
            $where[] = ['vp_title|shop_title', '=', $data['keyword']];
        }

        return $where;
    }


    /**
     * 虚码列表分页
     */
    public function virtual_page()
    {
        try {
            $getData = input('get.');
            $option = $this->formatOption($getData);
            $this->formatWhereUsedLog($getData, $option);

            $list = Services::VirtualUsedLog()->virtualUsedLog($this->merId, $option);
            api_result(API_SUCCESS, '请求成功', $list);
        } catch (Exception $e) {
            api_result($e);
        }
    }


    /**
     * 虚码详情
     */
    public function virtual_info()
    {

        $data = input('get.');
        try {
            validate(VirtualUsedLogValid::class)->scene('info')->check($data);

            $page = Services::VirtualUsedLog()->getInfo($this->adminUser['mer_id'], $data['id']);
            api_result($page);
        } catch (Exception $e) {
            api_result($e);
        }
    }


    /**
     * 虚码提交审核
     */
    public function virtual_audit()
    {

        $data = input('post.');
        try {
            validate(VirtualUsedLogValid::class)->scene('audit')->check($data);
            Services::VirtualUsedLog()->submitAudit($this->adminUser['mer_id'], $data['id'], $data['status'], $this->adminUser['admin_id'], $data['memo']);
            api_result(API_SUCCESS, '审核成功', $data['id']);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码导出
     */
    public function virtual_excel_send()
    {
        $param = input('get.');
        try {
            $where = $this->getWhere($param);
            $data = Services::VirtualUsedLog()->getList($where, (int)$param['page_size'] ?? 100);
            if (empty($data)) {
                throw  new Exception('无导出数据', API_ERROR);
            }

            $res = Excel::getInstance()
                ->filename('虚码订单记录' . date('Y-m-d H:i:s'))
                ->excelData($data)
                ->excelTitles(['id' => '主键', 'vp_title' => '活动名称', 'product_title' => '商品名称', 'red_packet' => '红包', 'point' => '积分', 'shop_title' => '所属门店','salesman_name' => '导购信息', 'status_title' => '状态', 'create_at' => '扫码时间'])
                ->sendType('excel')
                ->send();
            if (!$res) {
                throw  new Exception('导出失败', API_ERROR);
            }
        } catch (Exception $e) {
            throw  $e;
        }
    }


    /**
     * 继续支付红包
     * @return void
     */
    public function pay_red_packet(): void
    {
        try {
            $ids = input('post.ids/a');
            if (empty($ids)) {
                api_result(API_ERROR, '记录ID不能为空');
            }
            $num = Services::VirtualUsedLog()->payRedPacket($this->merId, $ids);
            api_result(API_SUCCESS, '记录已提交', ['num' => $num]);

        } catch (Exception $e) {
            api_result($e);
        }
    }

}
